import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.easygoods.entity;"
typeMapping = [
        (~/(?i)bigint/)            : "Long",
        (~/(?i)int/)               : "Integer",
        (~/(?i)float|double/)      : "Double",
        (~/(?i)decimal|real/)      : "BigDecimal",
        (~/(?i)datetime|timestamp/): "Date",
        (~/(?i)date/)              : "Date",
        (~/(?i)time/)              : "Date",
        (~/(?i)/)                  : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}

def generate(table, dir) {
    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    new File(dir, className + ".java").withPrintWriter { out -> generate(out, table.getName().toUpperCase(), className, fields) }
}

def generate(out, tableName, className, fields) {
    out.println "package $packageName"
    out.println ""
    out.println "import com.easygoods.base.BaseEntity;"
    out.println "import lombok.Data;"
    out.println "import lombok.EqualsAndHashCode;"
    out.println ""
    out.println "import javax.persistence.Id;"
    out.println "import java.math.BigDecimal;"
    out.println "import java.util.Date;"
    out.println ""
    out.println "@Data"
    out.println "@EqualsAndHashCode(callSuper = true)"
    out.println "public class $className extends BaseEntity {"
    fields.each() {
        out.println "    public static final String ${it.upper_name} = \"${it.name}\";"
    }
    out.println ""
    fields.each() {
        if (it.annos != "") out.println "    ${it.annos}"
        out.println "    private ${it.type} ${it.name};"
    }
    out.println "}"
}

def calcFields(table) {
    DasUtil.getColumns(table).filter { col -> col.getName() != "id" && col.getName() != "create_time" && col.getName() != "update_time" }.reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        def annos = DasUtil.isPrimary(col) ? "@Id" : ""
        fields += [[
                           upper_name: Case.UPPER.apply(col.getName()),
                           name      : javaName(col.getName(), false),
                           type      : typeStr,
                           annos     : annos]]
    }
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
